package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"video-guard/models/cache"
	"video-guard/models/mysql"

	"video-guard/videorpc/internal/svc"
	"video-guard/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *videorpc.RegisterRequest) (*videorpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.UserInfo
	err := user.RegisterUser(mysql.DB, in.PhoneNum)
	if err != nil {
		return nil, errors.New("错误")
	}
	if user.ID != 0 {
		return nil, errors.New("该手机号已注册，可直接登录")
	}
	key := fmt.Sprintf("游客_%d", rand.Intn(9000)+1000)
	user = mysql.UserInfo{
		PhoneNum:   in.PhoneNum,
		Password:   in.Password,
		NickName:   key,
		AvatarLink: "http://t4ka0fnml.hn-bkt.clouddn.com/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202025-10-29%20100739.png",
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.PhoneNum).Result()
	if result == "" {
		return nil, errors.New("未发送短信")
	}

	if in.SendSms != result {
		return nil, errors.New("短信错误")
	}
	err = user.UserAdd(mysql.DB)
	if err != nil {
		return nil, errors.New("注册失败")
	}
	return &videorpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
